package com.liyujie.networkrequest.utils.serialport;

import com.blankj.utilcode.util.SPUtils;
import com.liyujie.networkrequest.mobile.event.MessageEvent;
import com.liyujie.networkrequest.mobile.event.MessageType;
import com.liyujie.networkrequest.utils.CommonUtils;
import com.liyujie.networkrequest.utils.InitializeUtils;

import org.greenrobot.eventbus.EventBus;

import android_serialport_api.SerialPortFinder;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

public class SwipeCard {
    private static SerialPortFinder mSerialPortFinderCardSerialPort;
    private static SerialHelper mSerialHelperCardSerialPort;
    /**
     * 初始化刷卡串口
     */
    public static void initializeCreditCardSerialPort(){
        mSerialPortFinderCardSerialPort = new SerialPortFinder();
        mSerialHelperCardSerialPort = new SerialHelper(SPUtils.getInstance().getString("CreditCardSerialPort","/dev/ttyS2"), 9600) {
            @Override
            protected void onDataReceived(ComBean comBean) {
                if(null != comBean && null != comBean.bRec && comBean.bRec.length > 0){
                    String mSwipeCard = CommonUtils.bytesToHex(comBean.bRec);
                    EventBus.getDefault().post(new MessageEvent(MessageType.SwipeCardContent).put(mSwipeCard));
                }
            }
        };
        mSerialHelperCardSerialPort.setDataBits(8);//数据位
        mSerialHelperCardSerialPort.setParity(0);//校验位
        mSerialHelperCardSerialPort.setStopBits(1);//停止位
        mSerialHelperCardSerialPort.setFlowCon(0);//流控
        try {
            mSerialHelperCardSerialPort.open();//开启串口
            InitializeUtils.getDefaultMaker().show("刷卡串口开启成功"  + mSerialHelperCardSerialPort.getPort());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }

    /**
     * 获取全部串口信息
     * @return
     */
    public static String[] getAllDevicesPath(){
        return mSerialPortFinderCardSerialPort.getAllDevicesPath();
    }

    /**
     * 关闭串口
     */
    public static void close(){
        mSerialHelperCardSerialPort.close();
    }







}
